package com.ying.dogying.im;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.ying.dogying.entity.Const;
import com.ying.dogying.im.handler.MessageHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.server.handler.IWsMsgHandler;

import java.util.Map;

/**
 * 最主要的逻辑处理类，必须要写，否则，抛异常
 */
@Component
public class ImMessageHandler implements IWsMsgHandler {

    private static final Logger logger = LoggerFactory.getLogger(ImMessageHandler.class);

    /**
     * 握手时走这个方法，业务可以在这里获取Cookie，request参数等
     */
    @Override
    public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {

        // 绑定个人通道
        String userId = httpRequest.getParam("userId");
        String username = httpRequest.getParam("username");
        logger.info("ImMessageHandler---------------->{}:{}:正在握手", userId, username);
        Tio.bindUser(channelContext, userId);

        return httpResponse;
    }

    @Override
    public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {

        // 绑定群聊通道，群名称叫：dog-group(狗帮)
        Tio.bindGroup(channelContext, Const.IM_GROUP_NAME);

        logger.info("ImMessageHandler---------------->{}:已绑定群", channelContext.getId());
        logger.info("ImMessageHandler---------------->握手成功");

    }

    @Override
    public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        System.out.println("接收到bytes消息");
        return null;
    }

    @Override
    public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        Tio.remove(channelContext, channelContext.userid + "退出群聊了");
        return null;
    }

    @Override
    public Object onText(WsRequest wsRequest, String text, ChannelContext channelContext) throws Exception {
        System.out.println("接收到text消息：" + text);

        Map map = JSONUtil.toBean(text, Map.class);

        String type = MapUtil.getStr(map, "type");
        String data = MapUtil.getStr(map, "data");

        MessageHandler messageHandler = MessageHandlerFactory.getMessageHandler(type);

        // 处理消息
        messageHandler.messageHandler(data, wsRequest, channelContext);

        return null;
    }
}
